<?php

class Add_Publish_Article_ShowForm_Validate_Acl extends Ext_Validate_Abstract
{
    protected $_articleId;
    
    public function __construct($articleId)
    {
        $this->_articleId  = $articleId;
    }
    
    public function isValid()
    {
        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        $roleId = Ext_User::getInstance()->show($userId)->buildRole()->role->roleId;
        $acl = Ext_Acl::getInstance()->build($roleId);
        
        if(!$this->_articleId){
            if(!$acl->isAllowed($roleId, 'article', 'create')){
                $this->addMessage('Access denied.');
                return false;
            }
            return true;
        }
        
        $article = App_Model_DbTable_Article::getInstance()->getRowById($this->_articleId);
        if(!$article){
            $this->addMessage('Access denied.');
            return false;
        }
        if($article['userId'] == $userId){
            $userProfile = App_Model_DbTable_User_Profile::getInstance()->getRowByUserId($userId);
            if(!$userProfile){
                $this->addMessage('User profile record not found.');
                return false;
            }

            $lastArticleId = $userProfile['lastArticleId'];
            if($lastArticleId == $this->_articleId){
                if(!$acl->isAllowed($roleId, 'article', 'create')){
                    $this->addMessage('Access denied.');
                    return false;
                }
                
                return true;
            }
            
            if(!$acl->isAllowed($roleId, 'article', 'update')){
                $this->addMessage('Access denied.');
                return false;
            }
            return true;
        }
        
        if(Ext_User::getInstance()->show($userId)->buildRole()->role->roleType != 'admin'){
            $this->addMessage('Access denied.');
            return false;
        }
        
        if(!$acl->isAllowed($roleId, 'article', 'update')){
            $this->addMessage('Access denied.');
            return false;
        }
        
        return true;
    }
}
